import sys
sys.path.append('..')
from app.routers.dhgam import aeds_router, dhcds_router, dhged_router, hgcn_router, hgpms_router, mplp_router, mvhand_router, thgad_router, thgrl_router, tsge_router
import importlib
import os
import sys
from starlette.middleware.base import BaseHTTPMiddleware
from fastapi import FastAPI,Request
import asyncio
from starlette.responses import Response, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from app.utils.logger import logger
from app.tools.redis_client import redis_client
from contextlib import asynccontextmanager
from app.routers import algo_code_router, bank_risk_router, drpa_router, evolution_predict_router, facetnet_router, medical_share_router


class TimeoutMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        try:
            return await asyncio.wait_for(call_next(request), timeout=2000.0)
        except asyncio.TimeoutError:
            return Response("请求超时", status_code=504)

class CustomHeaderMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        response = await call_next(request)
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
        response.headers["Access-Control-Allow-Headers"] = "*"
        return response

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时执行的代码
    print("应用启动")
    try:
        # 初始化 Redis 连接
        await redis_client.init_connection()
        logger.info("Redis connection initialized")
    except Exception as e:
        logger.error(f"Failed to initialize Redis connection: {str(e)}")
        # 如果 Redis 连接失败，可以选择是否要终止应用启动
        # sys.exit(1)
    yield
    # 关闭时执行的代码
    print("应用关闭")

app = FastAPI(lifespan=lifespan)
app.add_middleware(CustomHeaderMiddleware)
app.add_middleware(TimeoutMiddleware)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中建议明确指定允许的域名
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],  # 明确指定允许的方法
    allow_headers=["*"],
    expose_headers=["*"],  # 添加这行
    max_age=3600,  # 添加预检请求的缓存时间
)

app.include_router(facetnet_router.router,prefix="/facetnet", tags=["facetnet"])

# app.include_router(algo_code_router.router,prefix="/algo_code", tags=["algo_code"])
app.include_router(aeds_router.router,prefix="/api/aeds", tags=["基于随机森林的异常边检测"])
app.include_router(dhcds_router.router, prefix="/api/dhcds", tags=["动态异构图社区检测"])
app.include_router(dhged_router.router,prefix="/api/dhged", tags=["动态异构图异常事件检测"])
app.include_router(hgcn_router.router, prefix="/api/hgcn", tags=["HGCN"])
app.include_router(hgpms_router.router, prefix="/api/hgpms", tags=["异构图模式挖掘"])
app.include_router(mplp_router.router, prefix="/api/mplp", tags=["元路径链接预测"])
app.include_router(mvhand_router.router, prefix="/api/mvhand", tags=["MVHAND"])
app.include_router(thgad_router.router, prefix="/api/thgad", tags=["THGAD"])
app.include_router(thgrl_router.router, prefix="/api/thgrl", tags=["时序异构图表示学习"])
app.include_router(tsge_router.router, prefix="/api/tsge", tags=["TSGE算法"])
app.include_router(evolution_predict_router.router, prefix="/api/evolution_predict", tags=["演化预测"])

app.include_router(drpa_router.router, prefix="/api/drpa", tags=["DRPA算法"])
app.include_router(bank_risk_router.router, prefix="/api/bank_risk", tags=["银行风险分析"])
app.include_router(medical_share_router.router, prefix="/api/medical_share", tags=["医疗共享图谱"])


@app.get("/")
async def root():
    return JSONResponse(
        content={"message": "Hello World"},
        headers={
            "Access-Control-Allow-Origin": "*",
            "Cache-Control": "no-cache"
        }
    )

if __name__ == "__main__":
    import uvicorn
    print("Starting server on http://127.0.0.1:1122")
    uvicorn.run(
        app, 
        host="0.0.0.0", 
        port=1122,
        log_level="debug",  # 添加详细日志
        access_log=True     # 确保访问日志开启
    )
